from datetime import datetime, timedelta

from app.models import Mets, UserInfo
from app.models.workout_record import WorkoutRecord  # 导入WorkoutRecord模型
from app.models.body_metrics import BodyMetrics
from app.models.rdi import RDI
from app import db
import json
from sqlalchemy import func


class WorkOutService:
    def get_week_records(self, user_id):
        # 获取过去7天的数据
        end_date = datetime.now()
        start_date = end_date - timedelta(weeks=1)

        # 查询最近一周的运动记录
        workouts = WorkoutRecord.query.filter(
            WorkoutRecord.user_id == user_id,
            WorkoutRecord.created_at >= start_date,
            WorkoutRecord.created_at <= end_date
        ).order_by(WorkoutRecord.created_at).all()
        # 格式化数据以返回前端
        workout_data = {
            "dates": [],
            "weights": [],
            "avg_BPM": [],
            "waists": []
        }
        for workout in workouts:
            workout_data["dates"].append(workout.created_at.strftime("%Y-%m-%d"))
            workout_data["weights"].append(workout.weight)
            workout_data["avg_BPM"].append(workout.avg_BPM)  # Assuming avg_BPM represents blood sugar (if needed, adjust)
            workout_data["waists"].append(workout.waist)  # Assuming body_fat is waist measurement (if needed, adjust)

        # workout_data.append({
        #     "weight": workout.weight,
        #     "height": workout.height,
        #     "max_BPM": workout.max_BPM,
        #     "avg_BPM": workout.avg_BPM,
        #     "resting_BPM": workout.resting_BPM,
        #     "duration_hours": workout.duration_hours,
        #     "calories_burn": workout.calories_burn,
        #     "workout_type": workout.workout_type,
        #     "body_fat": workout.body_fat,
        #     "water_intake_L": workout.water_intake_L,
        #     "workout_frequency": workout.workout_frequency,
        #     "experience_level": workout.experience_level,
        #     "BMI": workout.BMI,
        #     "dream_weight": workout.dream_weight,
        #     "exercise": workout.exercise,
        #     "weather_conditions": workout.weather_conditions,
        #     "exercise_intensity": workout.exercise_intensity,
        #     "created_at": workout.created_at.strftime("%Y-%m-%d %H:%M:%S")
        # })
        # 返回一周数据
        return {"workouts": workout_data}, None

    def get_today_records(self, user_id):
        try:
            # 获取今天的日期（只保留年月日）
            today = datetime.today().date()

            # 查询今天的所有运动记录
            existing_record = WorkoutRecord.query.filter(
                WorkoutRecord.user_id == user_id,
                db.func.date(WorkoutRecord.created_at) == today
            ).first()

            # 如果没有记录，返回错误信息
            if not existing_record:
                return None, "No workout records found for today"
            exercise_str = existing_record.exercise  # 假设 exercise 是 JSON 格式字符串
            if exercise_str:  # 如果 exercise 字段不为空
                try:
                    # 将 exercise 字段解析为列表
                    exercise_str = json.loads(existing_record.exercise)
                    # 确保 exercise_data 是一个列表
                    if not isinstance(exercise_str, list):
                        exercise_data = []
                except json.JSONDecodeError:
                    exercise_str = ""  # 如果解析失败，设置为空字符串
            # 将查询到的记录转换为字典格式返回
            result = {
                    "duration_hours": existing_record.duration_hours,
                    "calories_burn": existing_record.calories_burn,
                    "exercise_intensity": existing_record.exercise_intensity,
                    "workout_type": existing_record.workout_type,
                    "created_at": existing_record.created_at.isoformat(),  # 格式化时间
                    "exercise": exercise_str  # 假设 exercise 是 JSON 格式字段
            }

            return result, None

        except Exception as e:
            print(f"Error fetching today's workout records: {str(e)}")
            return None, "Error fetching workout records"


    def get_workout_record(self, user_id, workout_id):
        """获取指定用户和运动记录ID的记录"""
        try:
            workout = WorkoutRecord.query.filter_by(user_id=user_id, id=workout_id).first()
            if workout is None:
                return {"message": "Workout record not found"}, 404

            workout_data = {
                "weight": workout.weight,
                "height": workout.height,
                "max_BPM": workout.max_BPM,
                "avg_BPM": workout.avg_BPM,
                "resting_BPM": workout.resting_BPM,
                "duration_hours": workout.duration_hours,
                "calories_burn": workout.calories_burn,
                "workout_type": workout.workout_type,
                "body_fat": workout.body_fat,
                "water_intake_L": workout.water_intake_L,
                "workout_frequency": workout.workout_frequency,
                "experience_level": workout.experience_level,
                "BMI": workout.BMI,
                "dream_weight": workout.dream_weight,
                "exercise": workout.exercise,
                "weather_conditions": workout.weather_conditions,
                "exercise_intensity": workout.exercise_intensity,
                "created_at": workout.created_at.strftime("%Y-%m-%d %H:%M:%S")
            }

            return workout_data, 200
        except Exception as e:
            return {"error": str(e)}, 500

    def add_workout_record(self, data):
        """添加新的运动记录"""
        user_id = data["user_id"]
        # 从BodyMetrics表获取weight、height、body_fat、BMI、dream_weight
        body_metrics = BodyMetrics.query.filter_by(user_id=user_id).first()
        if body_metrics:
            weight = body_metrics.weight
            height = body_metrics.height
            body_fat = body_metrics.body_fat
            BMI = body_metrics.BMI
            dream_weight = body_metrics.dream_weight
        else:
            # 如果没有找到body_metrics记录，则需要处理该情况
            weight = height = body_fat = BMI = dream_weight = None

        # 计算最近一周该用户的运动记录次数
        one_week_ago = datetime.today() - timedelta(days=7)
        workout_frequency = WorkoutRecord.query.filter(WorkoutRecord.user_id == user_id,
                                                       WorkoutRecord.created_at >= one_week_ago).count()

        workout_type = data.get('workout_type')
        exercise_intensity = data.get('exercise_intensity')

        # 获取met表中与workout_type和intensity相关的MET记录
        # met_record = Met.query.filter_by(workout_type=workout_type, intensity=exercise_intensity).first()

        try:
            # 创建新的运动记录
            new_workout = WorkoutRecord(
                user_id=user_id,
                weight=weight,
                height=height,
                max_BPM=data.get('max_BPM'),# 前端传入
                avg_BPM=data.get('avg_BPM'),# 前端传入
                resting_BPM=data.get('resting_BPM'),# 前端传入
                duration_hours=data.get('duration_hours'),# 前端传入
                # calories_burn=data.get('calories_burn'),
                workout_type=data.get('workout_type'),# 前端传入
                # met_id=met_record.met_id,  # 填充 MET 信息
                body_fat=body_fat,
                water_intake_L=data.get('water_intake_L'),# 前端传入
                workout_frequency=workout_frequency,
                experience_level=data.get('experience_level'),
                BMI=BMI,
                dream_weight=dream_weight,
                exercise=data.get('exercise'),
                weather_conditions=data.get('weather_conditions'),# 前端传入
                exercise_intensity=data.get('exercise_intensity'),# 前端传入
                created_at=datetime.now()
            )
            # 计算卡路里消耗并赋值给记录
            new_workout.calculate_calories()

            # 保存到数据库
            db.session.add(new_workout)
            # 更新身体数据
            self.update_body_metrics(data.get('user_id'), data)

            db.session.commit()

            return {"message": "Workout record added successfully"}, 201
        except Exception as e:
            db.session.rollback()
            return {"error": str(e)}, 500

    def add_sport_record(self, user_id, recSportItem):
        """根据用户user_id和当天日期添加运动记录"""
        # 获取当前日期（不包括时间）
        today = datetime.today().strftime('%Y-%m-%d')

        # 查找用户今天的运动记录
        workout_record = WorkoutRecord.query.filter_by(user_id=user_id).filter(WorkoutRecord.created_at.like(f'{today}%')).first()

        # 获取传递的运动记录数据
        title = recSportItem.get('title')
        tit = recSportItem.get('tit')
        desc = recSportItem.get('desc')  # 描述（字符串）
        calories_burn = recSportItem.get('calories_burn')  # 热量消耗（float类型）
        met_id = recSportItem.get('met_id')

        if workout_record:
            # 如果已有记录，取出现有的 exercise 字段内容并追加新的记录
            existing_exercise = json.loads(workout_record.exercise) if workout_record.exercise else []
            existing_exercise.append(recSportItem)  # 添加新的运动记录

            # 更新 workout_record 的 exercise 字段
            workout_record.exercise = json.dumps(existing_exercise)
            workout_record.calories_burn = workout_record.calories_burn + calories_burn  # 累加热量消耗（如果需要）

        else:
            # 如果没有记录，创建新的记录
            workout_record = WorkoutRecord(
                user_id=user_id,
                workout_type=f"{met_id}|{title}|{desc}",  # 运动类型
                exercise_intensity=tit,  # 运动强度
                calories_burn=calories_burn,  # 使用前端传递的 calories_burn
                exercise=json.dumps([recSportItem]),  # 将 recSportItem 包装成列表存储
            )

        # 保存到数据库
        try:
            db.session.add(workout_record)
            db.session.commit()
            return {"message": "运动记录添加成功"}, 201
        except Exception as e:
            db.session.rollback()
            return {"message": f"保存运动记录失败: {str(e)}"}, 500

    def update_or_create_workout_record(self,user_id, item, new_value, data):
        """更新或创建新的运动记录"""
        try:
            today = datetime.today().date()
            last_week_date = today - timedelta(days=7)

            existing_record = WorkoutRecord.query.filter(
                WorkoutRecord.user_id == user_id,
                db.func.date(WorkoutRecord.created_at) == today
            ).first()
            # print(existing_record)


            if existing_record:

                # Handle exercise fields
                if item == 'exercise':
                    # print(float(new_value['calories_burn']))
                    # 1. Accumulate duration_hours
                    existing_record.duration_hours += float(new_value['duration_hours'])
                    # 2. Update calories_burn
                    existing_record.calories_burn = float(new_value['calories_burn'])
                    # 3. Update exercise_intensity if the new one is higher
                    current_intensity = existing_record.exercise_intensity
                    new_intensity = new_value['exercise_intensity']
                    intensity_levels = {'轻度': 1, '中等强度': 2, '高强度': 3}
                    if intensity_levels.get(new_intensity, 0) > intensity_levels.get(current_intensity, 0):
                        existing_record.exercise_intensity = new_intensity
                        existing_record.workout_type = new_value['title']
                    # 4. Update the `exercise` field (append new exercise item if necessary)
                    if existing_record.exercise:
                        exercise_data = json.loads(existing_record.exercise)  # Convert JSON string to list
                    else:
                        exercise_data = []
                    # print(exercise_data)
                    exercise_item = {
                        "title": new_value['title'],
                        "tit": new_value['tit'],
                        "desc": new_value['desc'],
                        "met_id": new_value['met_id']
                    }
                    # Append the new exercise item
                    exercise_data.append(exercise_item)
                    # Serialize the list of exercises back into a JSON string
                    existing_record.exercise = json.dumps(exercise_data)
                    # print("还是在这?")
                    # Commit the changes to the database
                    # db.session.add(existing_record)
                    db.session.commit()
                    return {"message": "Workout record updated successfully",
                            "data": existing_record.to_dict()}, 200
                else:
                    # 更新已有记录
                    if hasattr(existing_record, item):
                        # print("错误不在这")
                        field = getattr(existing_record, item)
                        # 根据字段类型进行转换
                        if isinstance(field, (int, float)):
                            new_value = float(new_value) if isinstance(field, float) else int(new_value)

                        setattr(existing_record, item, new_value)
                        # 更新身体数据
                        if item in ['weight', 'height', 'body_fat', 'BMI', 'waist', 'hip', 'thigh']:
                            self.update_body_metrics(user_id, data)
                        # 更新 MET 信息和卡路里消耗
                        # if met_record:
                        #     # 重新计算卡路里消耗
                        #     calories_burned = met_record.met_value * weight * existing_record.duration_hours
                        #     existing_record.calories_burn = calories_burned

                        db.session.commit()
                        return {"message": "Workout record updated successfully", "data": existing_record.to_dict()}, 200
                    else:
                        return {"error": f"Invalid workout type '{item}'"}, 400

            else:
                # workout_record = WorkoutRecord(
                #     user_id=user_id,
                #     duration_hours=0,
                #     calories_burn=0,
                #     exercise=[],
                # )
                # 获取用户信息
                user = UserInfo.query.get(user_id)
                if not user:
                    return None, "User not found"

                # 获取用户身体数据
                body_metrics = BodyMetrics.query.filter_by(user_id=user_id).first()
                if not body_metrics:
                    return None, "Body metrics not found"
                    # 如果没有记录，则创建新记录
                workout_record = WorkoutRecord(
                    user_id=user_id,
                    age=user.age,
                    gender=user.gender,
                    weight=body_metrics.weight,
                    height=body_metrics.height,
                    body_fat=body_metrics.body_fat,
                    BMI=body_metrics.BMI,
                    waist=body_metrics.waist,
                    hip=body_metrics.hip,
                    thigh=body_metrics.thigh,
                    waist_hip_ratio=body_metrics.waist_hip_ratio,
                    dream_weight=body_metrics.dream_weight,
                    workout_frequency=1,  # 初次记录
                    # exercise=[],
                    duration_hours=0,
                    calories_burn=0,
                    created_at=datetime.now(),
                    updated_at=datetime.now()
                )
                # 获取用户健康数据
                # health_metrics = HealthMetrics.query.filter_by(user_id=user_id).first()
                # if not health_metrics:
                #     return None, "Health metrics not found"

                if body_metrics:
                    workout_record.age = user.age
                    workout_record.gender = user.gender
                    workout_record.weight = body_metrics.weight
                    workout_record.height = body_metrics.height
                    workout_record.body_fat = body_metrics.body_fat
                    workout_record.BMI = body_metrics.BMI
                    workout_record.waist = body_metrics.waist
                    workout_record.hip = body_metrics.hip
                    workout_record.thigh = body_metrics.thigh
                    workout_record.waist_hip_ratio = body_metrics.waist_hip_ratio
                    workout_record.dream_weight = body_metrics.dream_weight
                else:
                    return {"error": "User body metrics not found."}, 404
                # Calculate workout frequency in the last week
                workout_frequency = WorkoutRecord.query.filter(
                    WorkoutRecord.user_id == user_id,
                    WorkoutRecord.created_at >= last_week_date
                ).count()
                workout_record.workout_frequency = workout_frequency

                # 创建新记录
                if hasattr(existing_record, item):
                    field = getattr(existing_record, item)
                    # Handle the case of fields that are numeric (int, float)
                    if isinstance(field, (int, float)):
                        # Convert the new value to the correct type (float or int)
                        new_value = float(new_value) if isinstance(field, float) else int(new_value)
                        setattr(existing_record, item, new_value)
                    # Update body metrics if necessary (e.g., weight, height, BMI)
                    if item in ['weight', 'height', 'body_fat', 'BMI', 'waist', 'hip', 'thigh']:
                        self.update_body_metrics(user_id, data)

                # Handle exercise fields
                # if item == 'exercise':
                #     workout_record = WorkoutRecord(user_id=user_id)
                #     # Set the basic fields for the new workout record
                #     workout_record.duration_hours = float(new_value['duration_hours'])
                #     workout_record.calories_burn = new_value['calories_burn']
                #     workout_record.workout_type = new_value['title']
                #     workout_record.exercise_intensity = new_value['exercise_intensity']
                #     workout_record.exercise = [{
                #         "title": new_value['title'],
                #         "tit": new_value['tit'],
                #         "desc": new_value['desc'],
                #         "met_id": new_value['met_id']
                #     }]
                # 查找 RDI 数据并根据生活方式调整因子
                # lifestyle_type = data.get('lifestyle_type')
                # rdi_data = RDI.query.filter(RDI.gender == data['gender'],
                #                             RDI.age_low <= data['age'],
                #                             RDI.age_high >= data['age']).all()
                # 根据生活方式类型调整 RDI 数据
                # for rdi in rdi_data:
                #     rdi.adjust_for_lifestyle(lifestyle_type)
                db.session.add(workout_record)
                db.session.commit()

                return {"message": "Workout record created successfully", "data": workout_record.to_dict()}, 201

        except Exception as e:
            print(f"error:{str(e)}")
            db.session.rollback()
            return {"error": str(e)}, 500


    def update_body_metrics(self, user_id, data):
        """根据运动数据更新身体数据"""
        try:
            body_metrics = BodyMetrics.query.filter_by(user_id=user_id).first()
            if body_metrics:
                workout_type = data['type']
                if workout_type in ['weight', 'height']:  # 更新体重或身高
                    if workout_type == 'weight':
                        body_metrics.weight = float(data['value'])
                    elif workout_type == 'height':
                        body_metrics.height = float(data['value'])

                    # 计算BMI
                    if body_metrics.weight and body_metrics.height:
                        BMI = (body_metrics.weight / (body_metrics.height ** 2))
                        body_metrics.BMI = round(BMI, 1)
                db.session.commit()
        except Exception as e:
            print("Error in update_body_metrics:", str(e))
            return {"error": str(e)}, 500

